package site.qjdb.controller;


import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import site.qjdb.constant.Info;
import site.qjdb.pojo.Notice;
import site.qjdb.pojo.User;
import site.qjdb.pojo.Want;
import site.qjdb.pojo.response.CommonResult;
import site.qjdb.pojo.response.ResponseCode;
import site.qjdb.service.NoticeService;
import site.qjdb.service.UserService;
import site.qjdb.service.WantService;
import site.qjdb.util.CommonUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;

@Controller
@RequestMapping("/want")
public class WantController {
	@Resource
	private UserService userService;
	@Resource
	private WantService wantService;
	@Resource
	private NoticeService noticeService;
	
	/**
	 *	添加求购信息
	 * 	content：留言内容，必传
	 * 	@throws UnsupportedEncodingException 
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public Object add(@RequestParam String content,
			HttpServletRequest request,
			HttpServletResponse response,
			HttpSession session) throws UnsupportedEncodingException {
		// 处理session和Cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if (i == 0) {
			return new CommonResult<>(ResponseCode.UNLOGIN);
		}
		if ("".equals(content.trim())) {
			return new CommonResult<>(ResponseCode.INCORECT_FORMAT);
		}
		// 解决特殊字符是空白的问题
		content = URLDecoder.decode(URLEncoder.encode(content, "UTF-8"),"UTF-8");
		// 添加求购信息
		Want want = new Want();
		// 求购内容
		want.setContent(content);
		// 未删除
		want.setIsDel(0);
		// 点赞数0
		want.setLikeCount(0);
		// 时间
		want.setTime(new Date());
		// 发布求购信息的用户
		User _user = new User();
		_user.setUid((((User) session.getAttribute(Info.USER_SESSION)).getUid()));
		want.setUser(_user);
		// 添加求购信息
		wantService.addWant(want);
		// 设置通知
		Notice notice = new Notice();
		// 对应求购信息id
		notice.setWid(want.getWid());
		// 未删除
		notice.setIsDel(0);
		// 新通知
		notice.setIsNew(1);
		// 类型：发布了新的求购信息（30）
		notice.setType(30);
		// 时间
		notice.setTime(new Date());
		// 接收用户
		notice.setUid(_user.getUid());
		// 添加通知
		noticeService.addNotice(notice);
		return new CommonResult<>(ResponseCode.SUCCESS, want);
	}
	
	/**
	 * 	增加点赞数
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/like", method = RequestMethod.POST)
	public Object like(@RequestParam("id") String wid, 
			HttpServletRequest request, 
			HttpServletResponse response, 
			HttpSession session) {
		// 处理session和Cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if (i == 0) {
			return new CommonResult<>(ResponseCode.UNLOGIN);
		}
		Integer widInteger = null;
		try {
			widInteger = Integer.parseInt(wid);
			// 根据wid查找Want，查看是否存在
			Want _want = new Want();
			_want.setIsDel(0);
			_want.setWid(widInteger);
			Want newWant = wantService.findWant(_want);
			if(newWant == null) {
				throw new Exception();
			}
			// 增加点赞数
			wantService.addLikeCount(newWant);
			// 设置通知
			Notice notice = new Notice();
			// 对应求购信息id
			notice.setWid(widInteger);
			// 未删除
			notice.setIsDel(0);
			// 新通知
			notice.setIsNew(1);
			// 类型：赞了我的求购信息（21）
			notice.setType(21);
			// 时间
			notice.setTime(new Date());
			// 接收用户
			notice.setUid(newWant.getUser().getUid());
			// 设置点赞用户
			notice.setOtherUid(((User)session.getAttribute(Info.USER_SESSION)).getUid());
			// 添加通知
			noticeService.addNotice(notice);
			return new CommonResult<>(ResponseCode.SUCCESS);
		} catch(Exception e) {
			return new CommonResult<>(ResponseCode.INCORECT_FORMAT);
		}
	}
	
	/**
	 * 	得到所有求购信息
	 * 	wd：关键字
	 * 	id: 用户id
	 * 
	 * */
	@ResponseBody
	@RequestMapping("/getWants")
	public Object getWants(
			@RequestParam(value = "wd", required = false) String keyword,
			@RequestParam(value = "id", required = false) String flag,
			HttpServletRequest request, 
			HttpServletResponse response, 
			HttpSession session){
		Want want = new Want();
		try {
			if(keyword != null && !"".equals(keyword.trim())) {
				want.setContent(keyword);
			}
			if(flag != null && "true".equals(flag)) {
				// 处理session和Cookie过期问题
				int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
				if (i == 0) {
					return new CommonResult<>(ResponseCode.UNLOGIN);
				}
				User user = new User();
				Integer uid = ((User)session.getAttribute(Info.USER_SESSION)).getUid();
				user.setUid(uid);
				want.setUser(user);
				// 清除新通知标记
				noticeService.clearNew(uid, 3);
			}
			return new CommonResult<>(ResponseCode.SUCCESS, wantService.findWantAll(want));
		}catch(Exception e) {
			return new CommonResult<>(ResponseCode.INCORECT_FORMAT);
		}
	}
	
	/**
	 * 得到活跃用户
	 * 
	 * */
	@ResponseBody
	@RequestMapping("/activeUser")
	public Object activeUser(HttpSession session) {
		return new CommonResult<>(ResponseCode.SUCCESS, session.getServletContext().getAttribute(Info.ACTICE_USER_APPLICATION));
	}
}
